#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define BUF_SIZE 1024 * 1024

int open_file(char *file_name, int flag)
{
    int fd = open(file_name, flag);
    if (fd == -1)
    {
        perror("open file failed");
        exit(1);
    }
    return fd;
}

int copy_file(int src_fd, int dst_fd)
{
    char *buf = (char *)malloc(BUF_SIZE);
    while (1)
    {
        memset(buf, 0, BUF_SIZE);
        int n = read(src_fd, buf, BUF_SIZE);
        if (n <= 0)
            break;
        write(dst_fd, buf, n);
    }
    free(buf);
}

void get_file_size(int fd)
{
    printf("file size: %d\n", lseek(fd, 0, SEEK_CUR));
}

void get_good()
{
    int f1 = open("3.txt", O_RDONLY);
    lseek(f1, -4, SEEK_END);
    char buff[5];
    memset(buff, 0, 5);
    read(f1, buff, 4);
    printf("%s\n", buff);
    close(f1);
}

int main()
{
    int fd1 = open_file("a.txt", O_RDONLY);
    int fd2 = open_file("b.txt", O_WRONLY | O_CREAT | O_TRUNC);

    copy_file(fd1, fd2);
    get_file_size(fd2);
    get_good();

    close(fd1);
    close(fd2);
}
